package ldh.serialize.type;

import java.io.IOException;

import ldh.serialize.BinarySerialized;
import ldh.serialize.io.ByteBuf;
import ldh.serialize.util.SerializedUtil;

public class EnumSerialized<T extends Enum<T>> implements BinarySerialized<T> {
	
	private Class<T> clazz;
	
	public EnumSerialized(Class<T> clazz) {
		this.clazz = clazz;
	}
	
	@Override
	public void write(ByteBuf out, T enums) throws IOException {
		String str;
		if (enums == null) {
			str = null;
		} else {
			str = enums.name();
		}
		SerializedUtil.writeString(out, str);
	}

	@Override
	public T read(ByteBuf in) throws IOException {
		String str = SerializedUtil.readString(in);
		if (str == null) {
			return null;
		}
		return Enum.valueOf(getClassType(), str);
	}

	@Override
	public Class<T> getClassType() {
		return clazz;
	}
}
